﻿using MebAppMarketplace.Biz;
using MebAppMarketplace.Common.Helpers;
using MebAppMarketplace.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MebAppMarketplace.Api
{
    [Authorize]
    [Route("api/[controller]/[action]")]
    public class UserController : Controller
    {
        public UserService userService { get; set; }
        [AllowAnonymous]
        public async Task<JsonResult> Login(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                ModelState.AddModelError("u", "请输入账号");
            }
            else if (string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("p", "请输入密码");
            }
            if (ModelState.IsValid)
            {
                var result = await userService.LoginUser(username, password);
                if (result == Model.LoginResult.登录成功)
                {
                    return this.JsonOk(userService.UserID.Value);
                }
                else
                {
                    return this.JsonError(result.ToString());
                }
            }
            else
            {
                return this.JsonErrorFromModelState();
            }
        }
        [AllowAnonymous]
        public JsonResult Register(string realName, string email, string message)
        {
            if (string.IsNullOrEmpty(realName))
            {
                ModelState.AddModelError("", "请填写真实姓名");
            }
            else if (!TextHelper.IsValidEmail(email))
            {
                ModelState.AddModelError("", "请填写有效的邮箱地址");
            }
            if (ModelState.IsValid)
            {
                userService.AddRegisterRequest(realName, email, message);
                return this.JsonOk();
            }
            return this.JsonErrorFromModelState();
        }
        [Authorize]
        public JsonResult Approve(Guid id)
        {
            if (userService.IsRegistrationAudited(id))
            {
                ModelState.AddModelError("", "已审核，不可重复审核");
            }
            if (ModelState.IsValid)
            {
                userService.ApproveRegistration(id);
                return this.JsonOk();
            }
            else
                return this.JsonErrorFromModelState();
        }
        [Authorize]
        public IActionResult Enable(Guid id, bool flag = true)
        {
            var m = userService.DbSet.Find(id);
            if (m == null)
                return this.JsonNotFound();
            else
            {
                if (flag)
                    userService.EnableUser(id);
                else
                    userService.DisableUser(id);
                return this.JsonOk();
            }
        }
    }
}
